import Request from 'luch-request'

// 创建简化的请求实例
const http = new Request({
  baseURL: 'http://localhost:8000/api', // 后端API地址
  timeout: 10000,
  header: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
http.interceptors.request.use(
  (config) => {
    // 添加token
    const token = uni.getStorageSync('token')
    if (token) {
      config.header = {
        ...config.header,
        'Authorization': `Bearer ${token}`
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    const { statusCode, data } = response
    
    if (statusCode === 200) {
      return data
    } else {
      uni.showToast({
        title: '请求失败',
        icon: 'none'
      })
      return Promise.reject(new Error('请求失败'))
    }
  },
  (error) => {
    uni.showToast({
      title: '网络错误',
      icon: 'none'
    })
    return Promise.reject(error)
  }
)

export default http